//
//  XLSafeLoginAlertView.m
//  industry
//
//  Created by xl on 2020/12/17.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLSafeLoginAlertView.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "XLUserDefaults.h"
#import "XLNetworking.h"
#import "XLPasswordView.h"
#import "XLGestureLockView.h"

@interface XLSafeLoginAlertView ()<XLPasswordViewDelegate, UIGestureRecognizerDelegate, XLGestureLockDelegate>

@property (nonatomic, strong) XLImageView *bgIG;
@property (nonatomic, strong) XLButton *exitBtn;
@property (nonatomic, strong) AUToast *toastLoad;

//数字密码登录
@property (nonatomic, strong) XLImageView *logoIG;
@property (nonatomic, strong) XLLabel *infosLB;
@property (nonatomic, strong) XLPasswordView *passwordView;

//手势密码登录
@property (nonatomic, strong) XLGestureLockView *lockView;

@property (nonatomic, assign) XLLoginWayType currentType;

@property (nonatomic, copy) void(^ResultSuccessBlock)(void);
@property (nonatomic, copy) void(^ResultFailBlock)(void);


@end

@implementation XLSafeLoginAlertView
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)showSafeLoginView:(XLLoginWayType)type {
    [self hideAllViews];
    self.currentType = type;
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    [self addSubview:self.bgIG];
    [_bgIG addSubview:self.logoIG];
    [_bgIG addSubview:self.infosLB];
    [self addSubview:self.exitBtn];
    [_bgIG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self);
    }];
    
    [_exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).offset(-16-SAFEAREA_BOTTOM_HEIGHT);
        make.left.equalTo(self).offset(20);
        make.size.mas_equalTo(CGSizeMake(78, 32));
    }];
    
    [_logoIG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgIG);
        make.top.equalTo(self.bgIG).offset(NAVIGATIONBAR_HEIGHT + 43);
        make.size.mas_equalTo(CGSizeMake(60, 61));
    }];
    
    [_infosLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logoIG.mas_bottom).offset(20);
        make.centerX.equalTo(self.logoIG);
    }];
    
    if (type == XLLoginWayTypePasswordUnlock) {//数字密码
        _infosLB.text = @"请输入解锁密码";
        [_bgIG addSubview:self.passwordView];
        [_passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.infosLB.mas_bottom).offset(40);
            make.left.equalTo(self.bgIG);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 60));
        }];
    } else if (type == XLLoginWayTypeGestureUnlock) {
        _infosLB.text = @"请绘制手势密码";
        [_bgIG addSubview:self.lockView];
        [_lockView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.infosLB.mas_bottom).offset(10);
            make.left.equalTo(self.bgIG);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH));
        }];
    } else {
        _infosLB.text = @"";
    }
}

//用faceID 或者 touchID  登录
- (void)loadLoginSuccessBlock:(void (^)(void))successBlock
                    failBlock:(void (^)(void))failBlock {
    self.ResultSuccessBlock = successBlock;
    self.ResultFailBlock = failBlock;
    
    if (self.currentType == XLLoginWayTypeBrushFaceUnlock ||
        self.currentType == XLLoginWayTypeFingerprintUnlock) {
        LAContext *myContext = [[LAContext alloc] init];
        // 这个属性是设置指纹输入失败之后的弹出框的选项
        myContext.localizedFallbackTitle = @"忘记密码";
        NSError *authError = nil;
        NSString *myLocalizedReasonString = @"请按住Home键完成验证";
        if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError])
            {
                [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:myLocalizedReasonString reply:^(BOOL success, NSError * _Nullable error) {
                    if(success)
                    {
                        NSLog(@"指纹认证成功");
                        [self requestUserTokenLoginSuccessBlock:successBlock failBlock:failBlock];
                    } else {
                        failBlock();
                        NSLog(@"指纹认证失败，%@",error.description);

                        NSLog(@"%ld", (long)error.code); // 错误码 error.code
                        switch (error.code)
                        {
                            case LAErrorAuthenticationFailed: // Authentication was not successful, because user failed to provide valid credentials
                            {
                                NSLog(@"授权失败"); // -1 连续三次指纹识别错误
                                BOOL can = [myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error];
                                if (can) {
                                    [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"连续3次指纹或者脸部识别错误，请再次指纹或脸部识别" reply:^(BOOL success, NSError * _Nullable error) {
                                        if (!error) {
                                             NSLog(@"密码输入成功！");
                                            [self requestUserTokenLoginSuccessBlock:successBlock failBlock:failBlock];
                                        } else {
                                            NSLog(@"密码输入错误！");
                                        }
                                    }];
                                }else{
                                    NSLog(@"调起账号密码页面失败!!!");
                                    
                                }
                            }
                                break;
                            case LAErrorUserCancel: // Authentication was canceled by user (e.g. tapped Cancel button)
                            {
                                NSLog(@"用户取消验证Touch ID"); // -2 在TouchID对话框中点击了取消按钮
                            }
                                break;
                            case LAErrorUserFallback: // Authentication was canceled, because the user tapped the fallback button (Enter Password)
                            {
                                NSLog(@"用户选择输入密码，切换主线程处理"); // -3
                            }
                                break;
                            case LAErrorSystemCancel: // Authentication was canceled by system (e.g. another application went to foreground)
                            {
                                NSLog(@"取消授权，如其他应用切入，用户自主"); // -4 TouchID对话框被系统取消，例如按下Home或者电源键
                            }
                                break;
                            case LAErrorPasscodeNotSet: // Authentication could not start, because passcode is not set on the device.
                            {
                                NSLog(@"设备系统未设置密码"); // -5
                            }
                                break;
                            case LAErrorTouchIDNotAvailable: // Authentication could not start, because Touch ID is not available on the device
                            {
                                NSLog(@"设备未设置Touch ID"); // -6
                            }
                                break;
                            case LAErrorTouchIDNotEnrolled: // Authentication could not start, because Touch ID has no enrolled fingers
                            {
                                NSLog(@"用户未录入指纹"); // -7
                            }
                                break;
                            case LAErrorTouchIDLockout: //Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite 用户连续多次进行Touch ID验证失败，Touch ID被锁，需要用户输入密码解锁，先Touch ID验证密码
                            {

                                BOOL can = [myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error];
                                if (can) {
                                    [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"连续多次指纹或者脸部识别错误，导致touchID或FaceID被锁定" reply:^(BOOL success, NSError * _Nullable error) {
                                        if (!error) {
                                             NSLog(@"密码输入成功！");
                                            [self requestUserTokenLoginSuccessBlock:successBlock failBlock:failBlock];
                                        } else {
                                            NSLog(@"密码输入错误！");
                                        }
                                    }];
                                }else{
                                    NSLog(@"调起账号密码页面失败!!!");
                                    
                                }
                                NSLog(@"Touch ID被锁，需要用户输入密码解锁"); // -8 连续五次指纹识别错误，TouchID功能被锁定，下一次需要输入系统密码
                            }
                                break;
                            case LAErrorAppCancel: // Authentication was canceled by application (e.g. invalidate was called while authentication was in progress) 如突然来了电话，电话应用进入前台，APP被挂起啦");
                            {
                                NSLog(@"用户不能控制情况下APP被挂起"); // -9
                            }
                                break;
                            case LAErrorInvalidContext: // LAContext passed to this call has been previously invalidated.
                            {
                                NSLog(@"LAContext传递给这个调用之前已经失效"); // -10
                            }
                                break;
                            default:
                            {
                                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                    NSLog(@"其他情况，切换主线程处理");
                                }];
                                break;
                            }
                        }
                    }
                }];
            }
            else
            {
                failBlock();
                NSLog(@"设备不支持指纹");
                NSLog(@"%ld", (long)authError.code);
                switch (authError.code)
                {
                    case LAErrorTouchIDNotEnrolled:
                    {
                        NSLog(@"Authentication could not start, because Touch ID has no enrolled fingers");
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        NSLog(@"Authentication could not start, because passcode is not set on the device");
                        break;
                    }
                    default:
                    {
                        NSLog(@"TouchID not available");
                        break;
                    }
                }
            }
    } else if (self.currentType == XLLoginWayTypePasswordUnlock) {//数字密码方式

    }

}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(nonnull UITouch *)touch {
    if ([touch.view isKindOfClass:[XLPasswordView class]]) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - XLPasswordViewDelegate
- (void)passWordDidChange:(XLPasswordView *)password {
    NSLog(@"改变%@", password.textStore);
    NSString *checkStr = password.textStore;
    if (checkStr.length < 4) {
        return;
    }
    NSString *lastPS = [XLUserDefaults getLastNumPassword];
    if (!ISEmptyString(lastPS) && [checkStr isEqualToString:lastPS]) {//校验通过
        [self requestUserTokenLoginSuccessBlock:self.ResultSuccessBlock failBlock:self.ResultFailBlock];
    } else {
        [XLToast showComonMessage:@"当前数字密码不对！"];
    }
}

-(void)passWordBeginInput:(XLPasswordView *)password
{
    NSLog(@"开始输入%@",password.textStore);
}

-(void)passWordCompleteInput:(XLPasswordView *)password
{
    NSLog(@"输入完成%@",password.textStore);
}

#pragma mark - XLGestureLockDelegate
- (void)gestureLockView:(XLGestureLockView *)lockView drawRectFinished:(NSMutableString *)gesturePassword {
    if (gesturePassword.length < 4) {
        _infosLB.text = @"至少连接四个点，请重新输入";
        [self shakeAnimationForView:_infosLB];
        [lockView clearLockView];
        return;
    }
    NSString *lastPS = [XLUserDefaults getLastGesturePassword];
    if (!ISEmptyString(lastPS) && [gesturePassword isEqualToString:lastPS]) {//校验通过
        [self requestUserTokenLoginSuccessBlock:self.ResultSuccessBlock failBlock:self.ResultFailBlock];
    } else {
        _infosLB.text = @"当前手势密码不对！";
        [self shakeAnimationForView:_infosLB];
        [lockView clearLockView];
    }
    XLLog(@"当前绘制密码%@", gesturePassword);
}

#pragma mark - UIButton
- (void)clickBgView {
    [self endEditing:YES];
}

- (void)clickExit {
    if (self.exitBlock) {
        self.exitBlock();
    }
    [self hideAllViews];
}

#pragma mark - Public
- (void)hideAllViews {
    self.ResultSuccessBlock = nil;
    self.ResultFailBlock = nil;
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    _bgIG = nil;
    _exitBtn = nil;
    _logoIG = nil;
    _infosLB = nil;
    _passwordView = nil;
    _lockView = nil;
    [self removeFromSuperview];
}

#pragma mark - Net
- (void)requestUserTokenLoginSuccessBlock:(void (^)(void))successBlock
                                failBlock:(void (^)(void))failBlock {
    XLHttpRequest *request = [[XLHttpRequest alloc] init];
    [self showLoadingAnimalWithTitle:@"登录中..."];
    WEAKSELF
    [request requestWithMethod:XLHttpMedthTypeGET url:XLUserTokenLoginUrl params:nil isExtraParams:NO successBlock:^(NSDictionary *dict) {
        STRONGSELF
        successBlock();
        [strongSelf hideLoadingAnimal];
        [strongSelf handleLoginData:dict];
        [strongSelf hideAllViews];
    } failBlock:^(XLServerRequestsStatus status, XLNetworkReachabilityStatus reachability, NSError *error, NSDictionary *dict) {
        STRONGSELF
        failBlock();
        [strongSelf hideLoadingAnimal];
    }];
}

#pragma mark - private
- (void)showLoadingAnimalWithTitle:(NSString *)title {
    dispatch_async(dispatch_get_main_queue(), ^{
         self.toastLoad = [XLToast showLoadingTitle:title superView:self];
    });
}

- (void)hideLoadingAnimal {
    dispatch_async(dispatch_get_main_queue(), ^{
         if (self.toastLoad) {
             [self.toastLoad dismissToast];
         }
        
    });

}

- (void)handleLoginData:(NSDictionary *)dict {
    id data = [dict objectForKey:@"data"];
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSDictionary *temDic = (NSDictionary *)data;
        //获取token
        NSString *token = [temDic objectForKey:@"token"];
        if (!ISEmptyString(token)) {
            [XLUserDefaults saveLastAvailableToken:token];
        }
        [XLNetworking updateCustomHeaderDicWithToken:token];
        
        //用户信息
        XLUserInfo *model = [XLUserInfo mj_objectWithKeyValues:data];
        XL_UserInfoData.keyId = model.keyId;
        XL_UserInfoData.keySecret = model.keySecret;
        XL_UserInfoData.securityToken = model.securityToken;
        [[XLUserData sharedXLUserData] saveCurrentUserInfo:XL_UserInfoData];
    }
}

// 抖动动画
- (void)shakeAnimationForView:(UIView *)view {
    
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 10, position.y);
    CGPoint right = CGPointMake(position.x + 10, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES]; // 平滑结束
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    
    [viewLayer addAnimation:animation forKey:nil];
}

#pragma mark - Setter/getter
- (XLImageView *)bgIG {
    if (!_bgIG) {
        _bgIG = [XLImageView new];
        _bgIG.contentMode = UIViewContentModeScaleAspectFill;
        _bgIG.clipsToBounds = YES;
        _bgIG.userInteractionEnabled = YES;
        _bgIG.image = XLIMAGE(@"dlbg");
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBgView)];
        tap.delegate = self;
        [_bgIG addGestureRecognizer:tap];
    }
    return _bgIG;
}

- (XLButton *)exitBtn {
    if (!_exitBtn) {
        _exitBtn = [XLButton new];
        _exitBtn.titleLabel.font = [UIFont fontOfPingFangSCSemiboldWithSize:15];
        _exitBtn.backgroundColor = [UIColor clearColor];
        [_exitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _exitBtn.layer.cornerRadius = 4.0;
        _exitBtn.layer.borderWidth = 1.0;
        _exitBtn.layer.borderColor = [UIColor whiteBgColor].CGColor;
        _exitBtn.layer.masksToBounds = YES;
        [_exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [_exitBtn addTarget:self action:@selector(clickExit) forControlEvents:UIControlEventTouchUpInside];
    }
    return _exitBtn;
}

- (XLImageView *)logoIG {
    if (!_logoIG) {
        _logoIG = [XLImageView new];
        _logoIG.image = XLIMAGE(@"logo_w");
    }
    return _logoIG;
}

- (XLLabel *)infosLB {
    if (!_infosLB) {
        _infosLB = [XLLabel new];
        _infosLB.font = [UIFont fontOfPingFangSCRegularWithSize:15];
        _infosLB.textColor = [UIColor whiteColor];
    }
    return _infosLB;
}

- (XLPasswordView *)passwordView {
    if (!_passwordView) {
        _passwordView = [[XLPasswordView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
        _passwordView.backgroundColor = [UIColor clearColor];
        _passwordView.delegate = self;
    }
    return _passwordView;
}

- (XLGestureLockView *)lockView {
    if (!_lockView) {
        _lockView = [[XLGestureLockView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        _lockView.backgroundColor = [UIColor clearColor];
        _lockView.delegate = self;
    }
    return _lockView;
}

@end
